<?php
declare (strict_types=1);
namespace app\course\model\coupon\admin;

use app\admin\model\market\ticket\TicketCoupon;
use app\common\helper\util\SnowFlake;
use app\common\model\BaseModel;
use app\course\event\subscribes\coupon\CouponUser as CouponUserSubscribe;
use app\user\model\user\admin\Account;
use think\facade\Event;
use think\helper\Str;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;

/**
 * 用户卡券模型
 */
class CouponUser extends BaseModel
{
    use SoftDelete;

    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'coupon_user';
    protected $append = ['status_text'];

    /**
     * 设置自动写入时间
     *
     * @var boolean
     */
    protected $autoWriteTimestamp = true;


    protected static $couponPrefix = [
        1 => 'YhQ', // 优惠券
        2 => 'DzK', // 打折卡
        3 => 'KcK', // 课程卡
    ];

    public function getStatusTextAttr($value, $data): string
    {
        $text = [
            0 => '未使用',
            1 => '已使用',
            2 => '已生成订单',
        ];

        return $text[$data['status']];
    }

    /**
     * 卡券信息
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-15
     */
    public function coupon(): BelongsTo
    {
        return $this->belongsTo(Coupon::class, 'coupon_id');
    }

    /**
     * 卡券领取用户
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-15
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'user_id')->removeOption('soft_delete')->removeWhereField('mhm_id')->bind(['phone', 'nick_name']);
    }

    /**
     * 关联活动券信息
     *
     * @return BelongsTo|void
     */
    public function ticket()
    {
        if ($this->getData('ticket_id')) {
            return $this->belongsTo(TicketCoupon::class, 'ticket_id', 'id')->removeWhereField('mhm_id')->bind([
                'issue_no'    => 'ticket_issue_no',
                'coupon_type' => 'ticket_coupon_type',
                'maxprice'    => 'ticket_maxprice',
                'price'       => 'ticket_price',
                'discount'    => 'ticket_discount',
            ]);
        }
    }

    /**
     * 新增数据事件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-13
     *
     * @param    [type]                         $coupon [description]
     */
    public static function onBeforeInsert($model)
    {
        // 卡号生成
        $model->code = self::$couponPrefix[$model->coupon_type] . app(SnowFlake::class)->nextId() . Str::random(8);
        unset($model->coupon_type);
    }

    /**
     * 新增数据完成之后
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-15
     *
     * @param    [type]                         $coupon [description]
     */
    public static function onAfterInsert($coupon)
    {
        Event::subscribe(CouponUserSubscribe::class);
        Event::trigger('CouponGrant');
    }

}
